package tw.com.msig.b2c.car.security.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import tw.com.msig.b2c.car.common.exception.ApplicationException;
import tw.com.msig.b2c.car.common.web.APILibDirector;
import tw.com.msig.b2c.car.common.web.BaseAction;
import tw.com.msig.b2c.car.security.service.AuthService;

public class AuthAction extends BaseAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String forwardPage = "login";

		String sActionType = request.getParameter("sActionType");

		if ("login".equals(sActionType)) {
			forwardPage = login(request, response);
		} else if ("logout".equals(sActionType)) {
			forwardPage = logout(request, response);
		}
		return mapping.findForward(forwardPage);
	}

	public String login(HttpServletRequest request, HttpServletResponse response) {

		String account = request.getParameter("account");
		String password = request.getParameter("password");

		log.debug("account={}, password={}", account, password);

		AuthService authService = (AuthService) APILibDirector
				.getSpringBean("authService");

		boolean isLogin = false;
		try {
			isLogin = authService.login(account, password);
		} catch (ApplicationException ex) {

			request.setAttribute("errorCode", ex.getCode());
			request.setAttribute("errorMessage", ex.getMessage());

		} catch (Exception ex) {
			ex.printStackTrace();
			request.setAttribute("errorCode", "error.unknown");
			request.setAttribute("errorMessage", "不明原因");

		}
		log.debug("isLogin={}", isLogin);

		if (isLogin) {

			HttpSession session = request.getSession();
			session.setAttribute("b2cUser", account);

			return "success";
		} else {

			return "login";
		}

	}

	public String logout(HttpServletRequest request,
			HttpServletResponse response) {
		HttpSession session = request.getSession();

		session.invalidate();

		return "login";

	}

}
